<template>
  <div class="template-B">
    <el-form :model="form" label-width="auto" style="display: flex; justify-content: space-between">
      <div style="display: flex">
        <el-form-item label="规则名称:">
          <el-input v-model="form.ruleName" placeholder="请输入" style="width: 200px" />
        </el-form-item>
        <el-form-item label="报告模板:" style="margin-left: 50px">
          <el-select
            v-model="form.reportTemplate"
            class="!w-240px"
            clearable
            placeholder="请选择报告类型"
          >
            <el-option
              v-for="dict in templateList"
              :key="dict.id"
              :label="dict.reportName"
              :value="dict.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 50px">
          <el-button type="primary" @click="query">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </div>
    </el-form>
    <div>
      <el-form-item style="display: flex">
        <el-button type="primary" @click="newAdd">新增</el-button>
        <el-button type="primary" @click="remove">删除</el-button>
      </el-form-item>
    </div>
    <div style="margin-top: 30px">
      <el-table
        :data="tableData"
        style="width: 100%"
        show-header
        @selection-change="handleSelectionChange"
        stripe
        header-cell-class-name="custom-header"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="规则名称" width="250" show-overflow-tooltip="" align="center" />
        <el-table-column prop="intensity" label="最大烈度范围" align="center" width="150"/>
        <el-table-column prop="population" label="灾区人口范围" align="center" width="150"/>
        <el-table-column prop="regionExtendDistance" label="外扩距离" align="center" width="150"/>
        <el-table-column prop="eqTypeName" label="地震类型" align="center" width="220"/>
        <el-table-column prop="templateName" label="报告模板" align="center" show-overflow-tooltip=""/>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="text" @click="view(row)" class="btn">查看</el-button>
            <el-button type="text" @click="edit(row)" class="btn">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 30px">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue'
import { ElFormItem, ElInput, ElButton } from 'element-plus'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { useRouter } from 'vue-router'
import * as datarApi from '@/api/report'

const router = useRouter()

defineOptions({ name: 'SystemDictType' })
const form = reactive({
  ruleName: '',
  reportTemplate: '',
  pageSize: 10,
  pageNo: 1
})
// 删除项
let idList = []
// 模板管理表格
const tableData = ref([])
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const size = ref('default')
const disabled = ref(false)
const background = ref(false)
const total = ref()
// 模板下拉列表
const templateList = ref([])
const emit = defineEmits(['addcreate', 'newView','modifyCreate']);
// 表格初始化
const getDataListRule = async () => {
  let formdata = new FormData()
  formdata.append('name', form.ruleName)
  formdata.append('templateId', form.reportTemplate)
  formdata.append('pageSize', form.pageSize)
  formdata.append('pageNo', form.pageNo)
  // const pageList = form
  try {
    const response = await datarApi.getListRule(formdata)
    const dataList = response.list
    const processedDataList = dataList.map((item) => {
      let intensity = item.intensity
      if (intensity.startsWith('>=')) {
        intensity = `≥${intensity.slice(2)}` // 例如: "≥100"
      } else if (intensity.startsWith('<=')) {
        intensity = `≤${intensity.slice(2)}` // 例如: "≤100"
      }
      // 处理 population 字段
      let population = item.population // 例如: ">=100" 或 "<=100"
      if (population.startsWith('>=')) {
        population = `≥${population.slice(2)}` // 例如: "≥100"
      } else if (population.startsWith('<=')) {
        population = `≤${population.slice(2)}` // 例如: "≤100"
      }
      return {
        ...item,
        intensity, // 更新 intensity 字段
        population // 更新 population 字段
      }
    })
    tableData.value = processedDataList
    // 分页数据
    total.value = response.total
  } catch (error) {
    console.log('失败')
    // 在这里处理异常
  }
}
// 选取的行数据
const handleSelectionChange = (selection) => {
  console.log(selection, '147')
  idList = []
  selection.forEach((item) => {
    idList.push(item.id)
  })
}

// 批量删除
const remove = async () => {
  // 显示确认对话框
  ElMessageBox.alert('是否确定删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback: async (action) => {
      console.log(action)
      if (action === 'confirm') {
        try {
          const response = await datarApi.deleteListRule(idList)
          ElMessage({
            type: 'success',
            message: '已删除！'
          })
          getDataListRule()
        } catch (error) {}
      } else {
        ElMessage({
          type: 'info',
          message: '已取消删除！'
        })
      }
    }
  })
}
// top1按钮区域
// 查询
const query = () => {
  getDataListRule()
  // console.log('已查询');
}
// 重置
const reset = () => {
  form.ruleName = ''
  form.reportTemplate = ''
}
// top2按钮区域
// 新增规则
const newAdd = () => {
  const eventPayload = {
    viewflag: false,
    state: 'addCreate'
  };
  emit('addCreate', eventPayload)
  // router.push({
  //   path: '/produce/addcreate'
  // })
}

// top3按钮区域
// 查看
const view = (row) => {
  const eventPayload = {
    rows:row,
    viewflag: false,
    state: 'newView'
  };
  emit('newView', eventPayload)
  // router.push({
  //   path: '/produce/newview',
  //   query: {
  //     rows: JSON.stringify(row)
  //   }
  // })
}
// 修改
const edit = (row) => {
  const eventPayload = {
    rows: row,
    viewflag: false,
    state: 'modifyCreate'
  };
  emit('modifyCreate', eventPayload)
  // router.push({
  //   path: '/produce/modifycreate',
  //   query: {
  //     rows: JSON.stringify(row)
  //   }
  // })
}

// 获取模板列表名称
const gettemplateList = async () => {
  try {
    const response = await datarApi.gettemplatedata()
    templateList.value = response
    console.log(response, '123')
  } catch (error) {
    console.log('失败')
    // 在这里处理异常
  }
}

//分页切换
const handleSizeChange = (val) => {
  form.pageSize = val
  getDataListRule()
}
const handleCurrentChange = (val) => {
  form.pageNo = val
  getDataListRule()
}
onMounted(() => {
  getDataListRule()
  gettemplateList()
})
</script>

<style scoped>
:deep(.custom-header) {
  background-color: #f2f3f5 !important;
  /* 设置表头背景色 */
  color: #333 !important;
  /* 设置表头文字颜色 */
  font-weight: bold !important;
  /* 设置表头文字加粗 */
  height: 42px;
}
.btn {
  border: none;
}
</style>
